package com.example.app.service;

import com.example.app.entity.BodyEntry;

import com.example.app.repository.BodyEntryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@Service
public class BodyEntryService {
    @Autowired
    private BodyEntryRepository repository;

    public List<BodyEntry> getAllEntries() {
        return repository.findAll();
    }

    public List<BodyEntry> getEntriesByUserId(Long userId) {
        return repository.findByUserId(userId);
    }

    public Optional<BodyEntry> getEntryByUserIdAndDate(Long userId, LocalDate date) {
        return repository.findByUserIdAndDate(userId, date);
    }

    public BodyEntry addOrUpdateEntry(BodyEntry entry) {
        // 如果该用户这天已填过，更新；否则新增
        return repository.findByUserIdAndDate(entry.getUserId(), entry.getDate())
                .map(existing -> {
                    existing.setFbg(entry.getFbg());
                    existing.setPbg(entry.getPbg());
                    existing.setSbp(entry.getSbp());
                    existing.setDbp(entry.getDbp());
                    existing.setWeight(entry.getWeight());
                    return repository.save(existing);
                })
                .orElseGet(() -> repository.save(entry));
    }

    public void deleteEntry(Long entryId) {
        repository.deleteById(entryId);
    }

    public boolean deleteByUserIdAndDate(Long userId, LocalDate date) {
        Optional<BodyEntry> entry = repository.findByUserIdAndDate(userId, date);
        if (entry.isPresent()) {
            repository.delete(entry.get());
            return true;
        } else {
            return false;
        }
    }
}
